package com.ggb.nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.sql.SQLOutput;
import java.util.Arrays;

public class NioTest11 {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel open = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(8899);
        open.socket().bind(inetSocketAddress);

        int messageLen = 2 + 3 + 4;
        ByteBuffer[] byteBuffers = new ByteBuffer[3];
        for (int i = 0; i < byteBuffers.length; i++) {
            byteBuffers[i] = ByteBuffer.allocate(i + 2);
        }
        SocketChannel accept = open.accept();

        while (true) {
            int byteRead = 0;
            while (byteRead < messageLen) {
                long r = accept.read(byteBuffers);
                byteRead += r;
                System.out.println("byteRead: " + byteRead);

                Arrays.stream(byteBuffers)
                        .map(byteBuffer -> "position:" + byteBuffer.position() + ",limit" + byteBuffer.limit())
                        .forEach(System.out::println);
            }
            Arrays.asList(byteBuffers).forEach(Buffer::flip);
            long bytesWritten = 0;
            while (bytesWritten < messageLen) {
                long r = accept.write(byteBuffers);
                bytesWritten += r;
            }
            Arrays.asList(byteBuffers).forEach(Buffer::clear);
            System.out.println("byteRead: " + byteRead + ", bytesWritten: " + bytesWritten + ", messageLen: " + messageLen);
        }

    }
}
